<template>
  <div class="enterprise-list">
    <!-- 头部区域 -->
    <div class="header">
      <div style="text-align: left;" v-if="parkData.length > 1">
        <el-select v-model="selectedParkValue" placeholder="请选择园区" :clearable="true" style="width: 300px"
          @change="handleSelectParkChange">
          <!-- 循环展示查询回来的数组数据 -->
          <el-option v-for="item in parkData" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <el-divider style="margin: 10px 0;" />
      </div>
      <!-- 统计卡片区域 -->
      <el-row :gutter="20" class="stats-card-row mb-4">
        <el-col :span="4" :xs="12" :sm="8" :md="6" :lg="4">
          <el-card class="stats-card" style="background:  linear-gradient(135deg, #fef9f2 0%, #fde6c8 100%);">
            <div class="stats-card-content">
              <p class="stats-card-label">已有园区</p>
              <p class="stats-card-value">{{ parkData.length }}</p>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4" :xs="12" :sm="8" :md="6" :lg="4">
          <el-card class="stats-card" style="background: linear-gradient(135deg, #e6f7ff 0%, #bae7ff 100%)">
            <div class="stats-card-content">
              <p class="stats-card-label">入住企业数</p>
              <p class="stats-card-desc">
                <span class="text-primary" style="color: gray;">
                  审核中：{{ enterprisePendingTotal }}
                </span>
              </p>
              <p class="stats-card-desc">
                <span class="text-primary" style="color: green;">
                  已入住：{{ enterpriseApprovedTotal }}
                </span>
              </p>
              <p class="stats-card-desc">
                <span class="text-primary" style="color: red;">
                  已离园：{{ enterpriseMovedOutTotal }}
                </span>
              </p>
            </div>
          </el-card>
        </el-col>
        <!-- 循环生成楼宇卡片：el-col 直接作为 el-row 的子元素 -->
        <el-col v-for="parkBuilding in ParkBuildings" :key="parkBuilding.buildingId" :span="4" :xs="12" :sm="8" :md="6"
          :lg="4" class="room-item">
          <el-card class="stats-card" style="background: linear-gradient(135deg, #f0f9ff 0%, #e1f3fd 100%)">
            <div class="stats-card-content">
              <p class="stats-card-label"> {{ parkBuilding.buildingName || '未知楼宇' }}({{ parkBuilding.buildingFloor ||
                '未知楼层' }}层)</p>
              <p class="stats-card-value">{{ parkBuilding.enterpriseSum }}</p>
              <p class="stats-card-desc">
                <span class="text-primary">
                  <i class="el-icon-info"></i> 入住企业数
                </span>
              </p>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4" :xs="12" :sm="8" :md="6" :lg="4">
          <el-card class="stats-card"  style="background: linear-gradient(135deg, #f9f2f2 0%, #f5f7fa 100%);">
            <div class="stats-card-content">
              <p class="stats-card-label">合同信息</p>
              <p class="stats-card-desc">
                <span class="text-primary" style="color: green;">
                  <i class="el-icon-info"></i> 已签：{{ signedContract }}
                </span>
              </p>
              <p class="stats-card-desc">
                <span class="text-primary" style="color: red;">
                  <i class="el-icon-info"></i> 未签：{{ noSignedContract }}
                </span>
              </p>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4" :xs="12" :sm="8" :md="6" :lg="4">
          <el-card class="stats-card" style="background: #f0fff4">
            <div class="stats-card-content">
              <p class="stats-card-label">房间使用率</p>
              <!-- <p class="stats-card-value">{{ roomRate }}%</p> -->
              <div class="kpi-value"
                :class="{ 'text-green': roomRate <= 90, 'text-red': roomRate > 90 }">
                {{ roomRate }}%
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <el-divider />
    <!-- 下面内容区域 -->
    <div class="container">
      <el-aside class="sidebar" :class="{ 'sidebar-collapsed': isCollapsed }" :width="isCollapsed ? '64px' : '240px'">
        <!-- 收缩/展开按钮 -->
        <div class="sidebar-header">
          <el-button icon="Expand" class="collapse-btn" @click="toggleCollapse"
            :title="isCollapsed ? '展开菜单' : '收起菜单'" />
        </div>
        <el-menu class="sidebar-menu" :default-active="currentRoutePath" :collapse="isCollapsed"
          :collapse-transition="false" :unique-opened="true" router>
          <el-menu-item index="/enterprise">
            <el-icon>
              <School />
            </el-icon>
            <template #title>企业管理</template>
          </el-menu-item>
          <el-menu-item index="/location">
            <el-icon>
              <HomeFilled />
            </el-icon>
            <template #title>入驻信息</template>
          </el-menu-item>
          <el-menu-item index="/contract">
            <el-icon>
              <Document />
            </el-icon>
            <template #title>合同管理</template>
          </el-menu-item>
          <el-menu-item index="/qualification">
            <el-icon>
              <Files />
            </el-icon>
            <template #title>资质文件</template>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <el-main class="main">
        <router-view :parkData="parkData" @callUpdateLoadAnalysisMethod="handleUpdateLoadAnalysisMethod" />
      </el-main>
    </div>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElLoading } from 'element-plus';
import request from '@/api/request'
import { useRoute } from 'vue-router'


// 控制侧边栏收缩状态
const isCollapsed = ref(false)
// 侧边栏宽度
const asideWidth = ref('200px')
// 切换侧边栏收缩状态
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
  // 根据状态设置不同宽度
  asideWidth.value = isCollapsed.value ? '60px' : '220px'
}

const route = useRoute()
// 数据存储
const parkData = reactive([]);
/**
 * 上面的统计表
 */
const selectedParkValue = ref('')//入住企业总数
const enterprisePendingTotal = ref(0)//入住审核中：企业总数
const enterpriseApprovedTotal = ref(0)//入住已入住：企业总数
const enterpriseMovedOutTotal = ref(0)//入住已离园：企业总数
const signedContract = ref(0)//已签合同
const noSignedContract = ref(0)//未签合同
const roomRate = ref(0)//房间使用率
const ParkBuildings = ref([])//
const parkId = ref(null)
// 动态绑定到 default-active：当前路由的完整路径
const currentRoutePath = ref('');
// 监听路由变化，更新激活的菜单
watch(
  () => route.path,
  (newPath) => {
    currentRoutePath.value = newPath;
  }
);

//页面初始化执行
onMounted(() => {
  //查询园区
  fetchParkData()
  //查询统计
  loadAnalysis()
  // 首次加载时手动同步路由
  currentRoutePath.value = route.path;
})
// 父组件的方法
const handleUpdateLoadAnalysisMethod = (params) => {
  console.log("子组件调用了父组件方法，参数：", params);
  //查询统计
  loadAnalysis()
};
//查询统计信息
const loadAnalysis = async () => {
  const res = await request.get("enterprise/getEnterpriseStatistics", {
    params: {
      parkId: parkId.value
    }
  })
  if (res.success) {
    enterprisePendingTotal.value = res.data.enterprisePendingTotal == null ? 0 : res.data.enterprisePendingTotal
    enterpriseApprovedTotal.value = res.data.enterpriseApprovedTotal == null ? 0 : res.data.enterpriseApprovedTotal
    enterpriseMovedOutTotal.value = res.data.enterpriseMovedOutTotal == null ? 0 : res.data.enterpriseMovedOutTotal
    signedContract.value = res.data.signedContract == null ? 0 : res.data.signedContract
    noSignedContract.value = res.data.noSignedContract == null ? 0 : res.data.noSignedContract
    roomRate.value = res.data.roomRate == null ? 0 : res.data.roomRate
    ParkBuildings.value = res.data.parkBuildings == null ? [] : res.data.parkBuildings
  }

}
//初始化查询园区信息
const fetchParkData = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '正在初始化页面数据...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  try {
    const myPartData = await request.get('park/page', {
      params: {
        pageNum: 1,
        pageSize: 999
      }
    })
    if (myPartData.success) {
      // 假设后端返回格式：{ list: [...园区数据...], total: 100 }
      // 直接替换 parkData 的内容（保持响应式）
      // parkData.splice(0, parkData.length, ...data.list);
      // 同时将数据返回给子组件
      parkData.splice(0, parkData.length, ...myPartData.data.list);
    }
  } catch (err) {
    parkData.length = 0; // 出错时清空数据
  } finally {
    loading.close()
  }
}
// 处理园区选中变化
const handleSelectParkChange = (value) => {
  parkId.value = value
  loadAnalysis()
};



</script>

<style scoped>
@import 'css/enterprise.css';
</style>